<?php
/**
 * Created by PhpStorm.
 * User: jiaruo
 * Date: 17/2/16
 * Time: 上午10:56
 */

namespace Api\Controller;


class FarmsController extends CommonController
{
    protected $userId = null;
    protected $animalPrice = null; // 价格
    protected $feedProce = null;//私聊价格
    protected $actricePrice = null;//激活码价格
    protected $robotprice = 0;//一键收取的价格

    public function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub
        $this->animalPrice = C('animalPrice');
        $this->feedProce = C('feedProce');
        $this->actricePrice = C('actricePrice');
        $this->robotprice = C('robotprice');

        if(IS_POST){
            $this->checkGet(array('token'));
            $this->userId = $this->tokenToUserId(I('post.token'));
        }
    }

    /**
     * 获得商品
     */
    public function getProducts()
    {
        $products = array(
            'animalPrice' => $this->animalPrice,
            'super' => C("superanimal"),    //超级ID
            'feedProce' => $this->feedProce,
            'actricePrice' => $this->actricePrice,
        );
        $this->echoJson($products);
    }

    /**
     * 购买牲畜
     */
    public function buyAnimal()
    {
        if(IS_POST){
            $time = strtotime(date('Y-m-d',time()).' 00:00:00');

            $buyNumber = M('user_animal')->where(
                array('userid'=>$this->userId,
                   // 'create_time'=>$time
                ))->count();

            if($buyNumber >= C('buyCycleMostNumber')){//判断机器总数，是否超出最大限制
                $this->echoJson(-12);
            }


          //  $type=I("post.type",0,"intval"); //购买的类型
            $costprice=C("animalPrice");  //购买时的花费
            if(0==$buyNumber)
            {
                $costprice=C("firstcost");
            }




            $user = $this->getUser($this->userId);
            if ($user['currency'] < $costprice)
            {//货币是否足够
                die(json_encode(array("code" => 400, "msg" => "咖啡数量不足,需要咖啡数量".$costprice,"currency"=>$user['currency'])));
            }
			
			$buyNumber = M('user_animal')->where(array('userid'=>$this->userId))->count();

			//消费金额
            $resutl = M('member')->where(array('id'=>$this->userId))->setDec('currency',$costprice);
            if($this->isFalse($resutl)){
                $this->echoJson(-1);
            }
            //$animalNo = $user['account'] .  strval( $buyNumber + 1);  //机器编号
            $animalNo =  strval( $buyNumber + 1);  //机器编号
            $lifeCycle = C('lifeCycle');//生命周期
            $expiredTime = time() + $lifeCycle * 86400;
            $animalResult = M('user_animal')->add(array(
                'userid' => $this->userId,
                'animal_on' => $animalNo,   //名称
                'create_time' => $time,
                'expired_time' => $expiredTime,
                'type' => 0,//普通机器
                'maxoutput' => C("maxoutput"),//普通机器的最大产出值
            ));


            if ($animalResult)
            {
                addLog($this->userId, '购买咖啡机', 1, $costprice);
              //  $this->echoJson(10000);

                $allnumber= M('user_animal')->where(
                    array('userid'=>$this->userId,
                        // 'create_time'=>$time
                    ))->count();

                $info = M('member')->field(' currency ')->where(array('id' => $this->userId))->find();
                die(json_encode(array("errcode" => 1000, "nums" => $allnumber, 'msg' => "购买成功", 'currency' => $info['currency'] ,'cost'=>$costprice)));
            }
        }
        $this->echoJson(-1);
    }



    /**
     * 购买超级机器的激活码
     */
    public function buyActrice()
    {
        if (IS_POST)
        {
            $user = $this->getUser($this->userId);
            if($user['buysuper'])
            {
                die(json_encode(array("code" => 400, "msg" => "你已经有特权了，不需要重复购买!")));
            }

            $costprice = $this->actricePrice;
            if ($user['currency'] < $costprice)
            {//货币是否足够
                die(json_encode(array("code" => 400, "msg" => "咖啡数量不足,需要咖啡数量" . $costprice, "currency" => $user['currency'])));
            }


            $resutl = M('member')->where(array('id' => $this->userId))->setDec('currency', $costprice);
            if ($this->isFalse($resutl))
            {
                $this->echoJson(-1);
            }

            //购买特权
            $feedResult = M('member')->where(array('id' => $this->userId))->save( array( 'buysuper'=> 1));
            if (false!==$feedResult)
            {
                addLog($this->userId, "购买超级机器的许可！", 3, $costprice);
                die(json_encode(array("code" => 200, "msg" => "购买权力成功!")));
                //$this->echoJson(10000);
            }
        }
        $this->echoJson(-1);
    }



    public function buysuper()
    {
        if(IS_POST){
            $time = strtotime(date('Y-m-d' ).' 00:00:00');

            $buyNumber = M('user_animal')->where(
                array('userid'=>$this->userId,
                    // 'create_time'=>$time
                ))->count();

            if($buyNumber >= C('buyCycleMostNumber')){//判断机器总数，是否超出最大限制
                $this->echoJson(-12);
            }


            $userinfo = M('member')->where(array('id' => $this->userId))->find();
            if(!$userinfo['buysuper'])
            {
                //用户没有权力，刚查询下级数量

                $count = M('member')->field('id,account,active,reg_time')->where(array('references' => $userinfo['account']))->count();
                if ($count >= C("SuperLowNumber"))
                {
                    //如果数量达到了，那么设置为可以购买，如果不可以那么提示
                   if(false== M('member')->where(array('id' => $this->userId))->save(array("buysuper" => 1)))
                   {
                       die(json_encode(array("errcode" => 400,"msg"=>"网络错误，错误码178")));

                   }//设置为可以购买
                } else
                {
                    die(json_encode(array("errcode" => 399, "msg" => '不能超级咖啡机，购买咖啡机需要直推50人以上，或者花费1500杯咖啡取得购买资格！')));
                }
                //判断用户是否有权力购买，给出提示
            }

            //  $type=I("post.type",0,"intval"); //购买的类型
            $costprice=C("superanimal");  //超级机器购买时的花费
            $user = $this->getUser($this->userId);
            if ($user['currency'] < $costprice)
            {//货币是否足够
                die(json_encode(array("code" => 400, "msg" => "咖啡数量不足,需要咖啡数量".$costprice,"currency"=>$user['currency'])));
            }

            $buyNumber = M('user_animal')->where(array('userid'=>$this->userId))->count();

            //消费金额
            $resutl = M('member')->where(array('id'=>$this->userId))->setDec('currency',$costprice);
            if($this->isFalse($resutl)){
                $this->echoJson(-1);
            }
           // $animalNo = $user['account'] .  strval( $buyNumber + 1);  //机器编号
            $animalNo =   strval( $buyNumber + 1);  //机器编号
            $lifeCycle = C('lifeCycle');//生命周期
            $expiredTime = time() + $lifeCycle * 86400;
            $animalResult = M('user_animal')->add(array(
                'userid' => $this->userId,
                'animal_on' => $animalNo,   //名称
                'create_time' => $time,
               // 'expired_time' => $expiredTime,
                'type' => 1,//超级咖啡机器
                'maxoutput' => C("supermax"),//普通机器的最大产出值
            ));


            if ($animalResult)
            {
                addLog($this->userId, '购买超级咖啡机', 1, $costprice);
                //  $this->echoJson(10000);

                $allnumber= M('user_animal')->where(array('userid' => $this->userId, 'type' => 1))->count();

                $info = M('member')->field(' currency ')->where(array('id' => $this->userId))->find();
                die(json_encode(array("errcode" => 1000, "nums" => $allnumber, 'msg' => "购买成功", 'currency' => $info['currency'] ,'cost'=>$costprice)));
            }
        }
        $this->echoJson(-1);
    }



    /**
     * 购买机器人
     */
    public function buyrobot()
    {

        if (IS_POST)
        {
            $user = $this->getUser($this->userId);
            $costprice= $this->robotprice;
            if ($user['currency'] < $costprice)
            {//货币是否足够
                die(json_encode(array("code" => 400, "msg" => "咖啡数量不足,需要咖啡数量".$costprice,"currency"=>$user['currency'])));
            }

            $resutl = M('member')->where(array('id' => $this->userId))->setDec('currency',$costprice);
            if ($this->isFalse($resutl))
            {
                die(json_encode(array("code" => 400, "msg" => "购买失败，错误码261") ));
            }




            $robotexp=C("robotexp"); //机器人过期时间
            $robotday=$user["robottime"];

            if($robotday<=time())
            {
                $exptime = strtotime("+{$robotexp} days");
            } else
            {
                $exptime = $robotday + (86400 * $robotexp);
            }



            $feedResult = M('member')->where(array('id' => $this->userId))->setField('robottime',$exptime );
            if ($feedResult)
            {
                addLog($this->userId, "购买一键打扫", 2, $costprice);
                die(json_encode(array("code" => 200, "msg" => "购买成功,到期时间为：".date("Y-m-d H:i:s",$exptime) ) ));
            }
        }
        $this->echoJson(-1);
    }


    /**
     * 购买饲料
     */
    public function buyFeed()
    {
        if(IS_POST){
            $user = $this->getUser($this->userId);
            if($user['currency'] < $this->feedProce){//货币是否足够
                $this->echoJson(-11);
            }
            $resutl = M('member')->where(array('id'=>$this->userId))->setDec('currency',$this->feedProce);
            if($this->isFalse($resutl)){
                $this->echoJson(-1);
            }
            $feedResult = M('member')->where(array('id'=>$this->userId))->setInc('feed',1);
            if($feedResult){
                addLog($this->userId,"购买饲料",2,$this->feedProce);
                $this->echoJson(10000);
            }
        }
        $this->echoJson(-1);
    }


	public function buyDan(){
		if(IS_POST){
			$num = I('post.num');
            $user = $this->getUser($this->userId);
            $market_price = M('market_price')->where(array('start'=>array('elt',date('Y-m-d'))))->order('start desc')->find();
			
			$price = $num * $market_price['price'];
			if($user['money'] < $price){
				$this->echoJson(-22);
			}
			if(M('member')->where(array('id'=>$this->userId))->setDec('money',$price)){
				M('member')->where(array('id'=>$this->userId))->setInc('currency',$num);
			}
			$this->echoJson(10000);
			
		}
		$this->echoJson(-1);
	}
	public function getPrice(){
		$market_price = M('market_price')->where(array('start'=>array('elt',date('Y-m-d'))))->order('start desc')->find();
		$this->echoJson($market_price);
		
	}

}